package com.ctsi.commons.event.man;

import com.ctsi.commons.event.EventPublisherMan;
import com.ctsi.commons.event.Observer;
import com.ctsi.commons.event.config.Event;
import com.ctsi.commons.event.config.EventModule;
import com.ctsi.commons.event.config.EventSource;
import com.ctsi.commons.util.UtilObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * 事件管理
 * 
 * @author zhangjw
 * 
 */
public class EventMan {
	private static final Logger log = LoggerFactory.getLogger(EventMan.class);

	/**
	 * 获取指定事件源的观察者
	 * 
	 * @param sourceId
	 * @return
	 */
	public List<Observer> getEventObserver(String sourceId) {
		return EventPublisherMan.getEventPublisherMan().getObservers(sourceId);
	}

	/**
	 * 获取模块下发布的事件
	 * 
	 * @param moduleId
	 * @return
	 */
	public List<EventSource> getModuleEventSouce(String moduleId) {
		EventPublisherMan ep = EventPublisherMan.getEventPublisherMan();
		List<EventModule> mList = ep.getModuleList();
		EventModule module = ep.getEventModuleById(mList, moduleId);
		if (module == null) {
			log.info("module {} not found", moduleId);
			return null;
		}

		return module.geteventSourceList();
	}

	/**
	 * 获取模块监听的事件
	 * 
	 * @param moduleId
	 * @return
	 */
	public List<Event> getModuleEvent(String moduleId) {
		EventPublisherMan ep = EventPublisherMan.getEventPublisherMan();
		List<EventModule> mList = ep.getModuleList();
		EventModule module = ep.getEventModuleById(mList, moduleId);
		if (module == null) {
			return null;
		}
		return module.getEventList();
	}

	public void disableObserver(String moduleId, String observerId) {
		List<Event> eList = getModuleEvent(moduleId);
		if (eList != null) {
			for (Event e : eList) {
				if (e.getId().equals(observerId)) {
					EventPublisherMan.getEventPublisherMan().disableOneObserver(e);
					return;
				}
			}
			log.warn("observer {} not found", observerId);
		}

	}

	/**
	 * 获取非本地的监听的事件列表,也可能是开发人员没有在publishevents中配置自己发布的信息
	 * @param addAll true部检查 false检查重复事件
	 * @return
	 */
	public List<Event> getNonLocalEvent(boolean addAll) {
		List<Event> result = new ArrayList<Event>();
		List<EventModule> ml = EventPublisherMan.getEventPublisherMan().getModuleList();
		for (EventModule em : ml) {
			List<Event> tem = em.getEventList();
			for (Event e : tem) {
				if (!EventPublisherMan.getEventPublisherMan().isLocalEvent(e.getEventid())) {
					if (addAll) {
						Event target = new Event();
						UtilObject.CopyBeanToBean(e, target);
						result.add(target);
					} else if (!checkEventId(result, e)) {
						Event target = new Event();
						UtilObject.CopyBeanToBean(e, target);
						result.add(target);
					}

					log.debug("event:{} not local", e);
				}
			}
		}
		return result;
	}

	private boolean checkEventId(List<Event> result, Event e) {
		for (Event er : result) {
			if (er.getEventid().equals(e.getEventid())) {
				return true;
			}
		}
		return false;
	}
}
